﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
public partial class DownLoad : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["userName"] == null || Session["roleID"] == null)
        {
            Response.Redirect("Login.aspx");
            Response.End();
        }
        if (Request.QueryString["filepath"] != null)
        {
            string filePath = Server.UrlDecode(Request.QueryString["filepath"]);
            string saveFileName = "files" + filePath;
            string extensionName = filePath.Substring(filePath.LastIndexOf(".") + 1).Trim().ToLower();
            switch (extensionName)
            {
                //case "doc":
                //case "docx":
                //    OpenWord(saveFileName); 
                //    break;
                //case "xls":
                //case "xlsx":
                //    OpenExcel(saveFileName);
                //    break;
                default: 
                    FileDownload(saveFileName);
                    break;

            }                       
        }
        else
        {
            Response.Write("<script language='javascript'>alert('非法操作!');location.href='MessageInfo.aspx'</script>");
        }
    }
    public void FileDownload(string FileName)
    {
       
        String FullFileName = System.Web.HttpContext.Current.Server.MapPath(FileName);
        FileInfo DownloadFile = new FileInfo(FullFileName);
        System.Web.HttpContext.Current.Response.Clear();
        System.Web.HttpContext.Current.Response.ClearHeaders();
        System.Web.HttpContext.Current.Response.Buffer = false;       
        System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(DownloadFile.Name, System.Text.Encoding.UTF8));        
        System.Web.HttpContext.Current.Response.AppendHeader("Content-Length", DownloadFile.Length.ToString());
        Response.ContentType = "application/octet-stream";
        System.Web.HttpContext.Current.Response.WriteFile(DownloadFile.FullName);
        System.Web.HttpContext.Current.Response.Flush();
        System.Web.HttpContext.Current.Response.End();
    }
    protected void OpenWord(string FileName)
    {
        Response.ContentType = "application/msword";
        Response.Redirect(FileName); 
    }
    protected void OpenExcel(string FileName)
    {
        Response.ContentType = "application/vnd.ms-excel";           
        Response.Redirect(FileName);
    }
}
